#!/bin/sh

###################################################################
# File Name: gen_ca_cert.sh
# Author: liaoxuecheng
# mail: liaoxuecheng@hotmail.com
# Created Time: 2025年02月28日 星期五 10时01分07秒
###################################################################


OT=$PWD/output

C='CN'
ST='GuangDong'
L='ShenZhen'
O='Self-Signed Certificate'
OU='R&D'
emailAddress='liaoxuecheng@hotmail.com'
CN='localhost'

gen_ca()
{
    #gen ca.crt
    local SUBJ="/C=$C/ST=$ST/L=$L/O=$O/OU=$OU/CN=$CN/emailAddress=$emailAddress"
    openssl req -newkey rsa:2048 -nodes -sha256 -config openssl.cnf -keyout ca.key -x509 -days 3652 -out ca.crt -subj "$SUBJ"
}

gen_chain_ca()
{
    #gen ca.crt
    gen_ca

    #gen ca2.crt
    local SUBJ="/C=$C/ST=$ST/L=$L/O=$O/OU=$OU/CN=$CN/emailAddress=$emailAddress"
    openssl req -newkey rsa:2048 -nodes -sha256 -config openssl.cnf -keyout ica.key -x509 -days 3652 -out ica.crt -subj "$SUBJ"

    #use ca.crt sign ca.crt  to gen secca.crt , extensions v3_ca0 limit some x509 filed functions
    openssl ca -ss_cert ica.crt -cert ca.crt -keyfile ca.key -out secca.crt -config openssl.cnf  -extensions v3_ca0

    cat ca.crt >> secca.crt
}

gen_cert()
{
# gen cert.crt
    local SUBJ="/C=$C/ST=$ST/L=$L/O=$O/OU=$OU/CN=$CN/emailAddress=$emailAddress"
    openssl req -newkey rsa:2048 -nodes -sha256 -config openssl.cnf -keyout client.key -out client.csr -subj "$SUBJ"

    openssl x509 -req -days 3652 -in client.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out client.crt
    #or chain sign
    #openssl x509 -req -days 3652 -in client.csr -CA secca.crt -CAkey ica.key -CAcreateserial -out client.crt

    #verify cert.cet
    openssl verify openssl verify -show_chain -CAfile  ca.crt  client.crt 
    #openssl verify openssl verify -show_chain -CAfile  secca.crt  client.crt
}

exit 0

#gen ca.crt
openssl req -newkey rsa:2048 -nodes -sha256 -config openssl.cnf -keyout ca.key -x509 -days 3652 -out ca.crt \
	-subj '/C=CN/ST=GuangDong/L=ShenZhen/O=Self-Signed Certificate/OU=R&D/CN=LiaoXuecheng/emailAddress=liaoxuecheng@hotmail.com'

#use ca sign ca
openssl ca -ss_cert ica.crt -cert ca.crt -keyfile ca.key -out secca.crt -config openssl.cnf  -extensions v3_ca0

# gen cert.crt
openssl req -newkey rsa:2048 -nodes -sha256 -config openssl.cnf -keyout client.key -out client.csr
	-subj '/C=CN/ST=GuangDong/L=ShenZhen/O=Self-Signed Certificate/OU=R&D/CN=LiaoXuecheng/emailAddress=liaoxuecheng@hotmail.com'

openssl x509 -req -days 3652 -in client.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out client.crt
